package com.iflytek.jzcpx.procuracy.cont.service.impl;

import java.util.*;
import java.util.concurrent.TimeUnit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.iflytek.jzcpx.procuracy.cont.common.constants.CacheKeyPrefixConstants;
import com.iflytek.jzcpx.procuracy.cont.service.RedisDataService;

@Service
public class RedisDataServiceImpl implements RedisDataService {

	@SuppressWarnings("rawtypes")

	@Autowired
	private RedisTemplate redisTemplate;

	// @Value("${argue.expireTime}")
	// private int expireTime;

	/**
	 * 根据key自增主键
	 * 
	 * @param key
	 * @return
	 */
	@Override
	public String generateKey(String key, int index) {
		/*
		 * RedisAtomicInteger redisAtomicInteger = new
		 * RedisAtomicInteger(key,redisTemplate.getConnectionFactory()); int originalId
		 * = 1; //获取code值 originalId = redisAtomicInteger.get(); //第一次，设置为1
		 * if(originalId==0) { redisAtomicInteger.set(1); } //获得后加1 int newId =
		 * redisAtomicInteger.incrementAndGet(); logger.info("fileId="+newId);
		 */

		// return edFileMapper.generateKey(key,index);
		return UUID.randomUUID().toString();
	}

	@Override
	public Map<String, Integer> getFailDetails(Integer dossierId) {
		Map<String, Integer> failMap = new HashMap<>();
		failMap.put("downloadFailNum", getKey(CacheKeyPrefixConstants.DOWNLOAD_FAIL_NUM + dossierId));
		failMap.put("uploadFailNum", getKey(CacheKeyPrefixConstants.UPLOAD_FAIL_NUM + dossierId));
		failMap.put("ocrFailNum", getKey(CacheKeyPrefixConstants.OCR_FAIL_NUM + dossierId));
		failMap.put("ocrSuccessNum", getKey(CacheKeyPrefixConstants.OCR_SUCCESS_NUM + dossierId));
		failMap.put("fileNum", getKey(CacheKeyPrefixConstants.FILE_NUM + dossierId));
		return failMap;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setDetails(Integer dossierId, Integer count, Integer isAppend) {
		// 用于计算总数，上传、OCR失败图片的数量
		redisTemplate.opsForValue().set(CacheKeyPrefixConstants.FILE_UPLOAD_NUM + dossierId, 0, 7, TimeUnit.DAYS);
		redisTemplate.opsForValue().set(CacheKeyPrefixConstants.FILE_NUM + dossierId, count, 7, TimeUnit.DAYS);
		redisTemplate.opsForValue().set(CacheKeyPrefixConstants.DOWNLOAD_FAIL_NUM + dossierId, 0, 7, TimeUnit.DAYS);
		redisTemplate.opsForValue().set(CacheKeyPrefixConstants.UPLOAD_FAIL_NUM + dossierId, 0, 7, TimeUnit.DAYS);
		redisTemplate.opsForValue().set(CacheKeyPrefixConstants.OCR_FAIL_NUM + dossierId, 0, 7, TimeUnit.DAYS);
		redisTemplate.opsForValue().set(CacheKeyPrefixConstants.OCR_SUCCESS_NUM + dossierId, 0, 7, TimeUnit.DAYS);
		redisTemplate.delete(CacheKeyPrefixConstants.OCR_FAIL_PATH + dossierId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void dataIncrements(String key, long delta) {
		synchronized (this) {
			redisTemplate.opsForValue().increment(key, delta);
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public void resetKey(String key, Integer value) {
		redisTemplate.opsForValue().set(key, value, 7, TimeUnit.DAYS);
	}

	@Override
	public Integer getKey(String key) {
		Object num = redisTemplate.opsForValue().get(key);
		num = num == null ? 0 : num;
		return Integer.valueOf(num.toString());
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setLongKey(String key, long value) {
		redisTemplate.opsForValue().set(key, value, 7, TimeUnit.DAYS);
	}

	@Override
	public Long getLongKey(String key) {
		Object num = redisTemplate.opsForValue().get(key);
		num = num == null ? 0 : num;
		return Long.valueOf(num.toString());
	}

	// 扫描入口ocr进度相关参数初始化
	public void setScanDetails(Integer dossierId, Integer isAppend) {
		resetKey(CacheKeyPrefixConstants.FILE_UPLOAD_NUM + dossierId, 0);
		resetKey(CacheKeyPrefixConstants.FILE_NUM + dossierId, 0);
		resetKey(CacheKeyPrefixConstants.OCR_FAIL_NUM + dossierId, 0);
		resetKey(CacheKeyPrefixConstants.UPLOAD_FAIL_NUM + dossierId, 0);
		resetKey(CacheKeyPrefixConstants.DOWNLOAD_FAIL_NUM + dossierId, 0);
		resetKey(CacheKeyPrefixConstants.OCR_SUCCESS_NUM + dossierId, 0);
		redisTemplate.delete(CacheKeyPrefixConstants.OCR_FAIL_PATH + dossierId);
	}

	//// 本地上传入口ocr进度相关参数初始化
	@Override
	public void setUploadDetails(Integer dossierId, Integer isAppend, Integer count) {
		resetKey(CacheKeyPrefixConstants.FILE_NUM + dossierId, count);
		resetKey(CacheKeyPrefixConstants.OCR_FAIL_NUM + dossierId, 0);
		resetKey(CacheKeyPrefixConstants.UPLOAD_FAIL_NUM + dossierId, 0);
		resetKey(CacheKeyPrefixConstants.DOWNLOAD_FAIL_NUM + dossierId, 0);
		resetKey(CacheKeyPrefixConstants.OCR_SUCCESS_NUM + dossierId, 0);
		redisTemplate.delete(CacheKeyPrefixConstants.OCR_FAIL_PATH + dossierId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setHashKeyList(String key, String hashKey, String path) {
		redisTemplate.opsForHash().put(key, hashKey, path);
	}

	@SuppressWarnings("unchecked")
	@Override
	public void removeFailPathByHashKey(String key, String hashKey) {
		redisTemplate.opsForHash().delete(key, hashKey);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List getHashKeyList(String key) {
		return redisTemplate.opsForHash().values(key);
	}

	@Override
	public void setArgueData(String key, String hashKey, String value) {

		int expireTime = 3;

		redisTemplate.opsForHash().put(key, hashKey, value);
		// 设置过期时间
		if (redisTemplate.opsForHash().size(key) == 1) {
			redisTemplate.expire(key, expireTime, TimeUnit.DAYS);
		}
	}

	@Override
	public String getArgueData(String key, String hashKey) {
		Object num = redisTemplate.opsForHash().get(key, hashKey);
		return num == null ? "" : num.toString();
	}

	/**
	 * 存入当天法院的分级码
	 * 
	 * @param key
	 *            当天日期
	 * @param hashKey
	 *            法院分级码
	 */
	@Override
	public void setArgueCourtList(String key, String hashKey) {
		if (StringUtils.isEmpty(key) || StringUtils.isEmpty(hashKey)) {
			return;
		}
		// 如果没有hashKey（法院分级码），则put进去
		if (!redisTemplate.opsForHash().hasKey(key, hashKey)) {
			redisTemplate.opsForHash().put(key, hashKey, 1);
		}
		// 设置有效期为1天
		if (redisTemplate.opsForHash().size(key) == 1) {
			redisTemplate.expire(key, 1, TimeUnit.DAYS);
		}
	}

	/**
	 * 获取当天法院的总数
	 * 
	 * @param key
	 *            当天日期
	 * @return
	 */
	@Override
	public int getArgueCourtCount(String key) {
		return redisTemplate.opsForHash().values(key).size();
	}

	@Override
	public void removeKey(String key) {
		// redisTemplate.delete(key);
		redisTemplate.expire(key, 0, TimeUnit.SECONDS);
	}

	@Override
	public boolean hasKey(String key) {
		if (redisTemplate.hasKey(key)) {
			return true;
		}
		return false;
	}

	@Override
	public void addZSet(String key, String fileId, String ocrJson, double score) {
		if (StringUtils.isEmpty(ocrJson)) {
			ocrJson = "{}";
		}
		JSONObject file_ocr = new JSONObject();
		String dossierId = key.substring(key.lastIndexOf("_") + 1);
		file_ocr.put("id", fileId + "_" + dossierId + "_" + (int) score);
		file_ocr.put("ocr_result", JSON.parseObject(ocrJson, JSONObject.class));
		redisTemplate.opsForZSet().add(key, file_ocr, score);
		redisTemplate.expire(key, 2, TimeUnit.HOURS);
	}

	@Override
	public Set getZSet(String key, long start, long end) {
		return redisTemplate.opsForZSet().range(key, 0, -1);
	}

	@Override
	public void replaceZSet(String key, double min, double max, String fileId, String ocrJson) {
		redisTemplate.opsForZSet().removeRangeByScore(key, min, max);
		addZSet(key, fileId, ocrJson, max);
	}

	@Override
	public void hashDataIncrements(String key, String hashKey, int i) {
		redisTemplate.opsForHash().increment(key, hashKey, i);
	}
}
